import 'dart:convert';
import 'package:dio/dio.dart';
import '../models/models.dart';
import '../utils/crypto_util_v2.dart';

class ApiService {
  static const String baseUrl = 'http://localhost:8080';
  late final Dio _dio;

  ApiService() {
    _dio = Dio(BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 10),
      headers: {
        'Content-Type': 'application/json',
      },
    ));

    // 添加拦截器
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        print('Request: ${options.method} ${options.path}');
        print('Request Data: ${options.data}');
        handler.next(options);
      },
      onResponse: (response, handler) {
        print('Response: ${response.statusCode}');
        print('Response Data: ${response.data}');
        handler.next(response);
      },
      onError: (error, handler) {
        print('Error: ${error.message}');
        handler.next(error);
      },
    ));
  }

  // 发送加密的POST请求
  Future<T> _sendEncryptedRequest<T>(
    String endpoint,
    Map<String, dynamic> data,
    T Function(Map<String, dynamic>) fromJson,
  ) async {
    try {
      // 1. 将数据转换为JSON字符串
      final jsonString = jsonEncode(data);
      print('Original JSON: $jsonString');

      // 2. 加密数据
      final encryptedData = CryptoUtil.encrypt(jsonString);
      print('Encrypted Data: $encryptedData');

      // 3. 创建加密请求
      final encryptedRequest = EncryptedRequest(data: encryptedData);

      // 4. 发送请求
      final response = await _dio.post(
        '/api$endpoint',
        data: encryptedRequest.toJson(),
      );

      // 5. 解析加密响应
      final encryptedResponse = EncryptedResponse.fromJson(response.data);
      
      if (!encryptedResponse.success) {
        throw Exception(encryptedResponse.message);
      }

      // 6. 解密响应数据
      final decryptedData = CryptoUtil.decrypt(encryptedResponse.data);
      print('Decrypted Response: $decryptedData');

      // 7. 解析JSON并返回对象
      final jsonData = jsonDecode(decryptedData);
      return fromJson(jsonData);
    } catch (e) {
      print('API Error: $e');
      throw Exception('API request failed: $e');
    }
  }

  // 发送加密的GET请求
  Future<T> _sendEncryptedGetRequest<T>(
    String endpoint,
    T Function(Map<String, dynamic>) fromJson,
  ) async {
    try {
      // GET请求不需要加密请求体，直接发送
      final response = await _dio.get('/api$endpoint');

      // 解析加密响应
      final encryptedResponse = EncryptedResponse.fromJson(response.data);
      
      if (!encryptedResponse.success) {
        throw Exception(encryptedResponse.message);
      }

      // 解密响应数据
      final decryptedData = CryptoUtil.decrypt(encryptedResponse.data);
      print('Decrypted Response: $decryptedData');

      // 解析JSON并返回对象
      final jsonData = jsonDecode(decryptedData);
      return fromJson(jsonData);
    } catch (e) {
      print('API Error: $e');
      throw Exception('API request failed: $e');
    }
  }

  // 登录
  Future<LoginResponse> login(String username, String password) async {
    final loginRequest = LoginRequest(username: username, password: password);
    return await _sendEncryptedRequest(
      '/login',
      loginRequest.toJson(),
      (json) => LoginResponse.fromJson(json),
    );
  }

  // 获取用户信息
  Future<UserData> getUser() async {
    return await _sendEncryptedGetRequest(
      '/user',
      (json) => UserData.fromJson(json),
    );
  }

  // 获取用户列表
  Future<List<UserData>> getUsers() async {
    try {
      final response = await _dio.get('/api/users');
      
      final encryptedResponse = EncryptedResponse.fromJson(response.data);
      
      if (!encryptedResponse.success) {
        throw Exception(encryptedResponse.message);
      }

      final decryptedData = CryptoUtil.decrypt(encryptedResponse.data);
      print('Decrypted Response: $decryptedData');

      final jsonData = jsonDecode(decryptedData);
      
      if (jsonData is List) {
        return jsonData.map((item) => UserData.fromJson(item as Map<String, dynamic>)).toList();
      } else {
        throw Exception('Expected list response');
      }
    } catch (e) {
      print('API Error: $e');
      throw Exception('API request failed: $e');
    }
  }

  // 创建用户
  Future<UserData> createUser(UserData user) async {
    return await _sendEncryptedRequest(
      '/users',
      user.toJson(),
      (json) => UserData.fromJson(json),
    );
  }

  // 健康检查（不加密）
  Future<Map<String, dynamic>> healthCheck() async {
    try {
      final response = await _dio.get('/health');
      return response.data;
    } catch (e) {
      throw Exception('Health check failed: $e');
    }
  }
}
